package com.aya.export.aspect;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.aya.export.annotation.ExcelExport;
import com.aya.export.finder.PropertyFinder;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.ReflectionUtils;

import java.io.File;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Random;

/**
 * @author ls9527
 * @date 2025/3/2
 */
public class LocalStorageTempSave {
    private File localFile;


    public LocalStorageTempSave() {
        Random random = new Random();
        String randomFileName = random.nextLong(1000000, 9999999) + "fileName.xlsx";
        localFile = new File(randomFileName);

    }


    public File getLocalFile() {
        return localFile;
    }


    private Object invokeMethod(Object bean, String methodName, Class<?>[] paramTypes, Object... args) {
        // 2. 反射查找方法
        Method method = ReflectionUtils.findMethod(bean.getClass(), methodName, paramTypes);
        if (method == null) {
            throw new IllegalArgumentException("Method not found: " + methodName);
        }

        // 3. 执行方法（支持私有方法）
        ReflectionUtils.makeAccessible(method);
        return ReflectionUtils.invokeMethod(method, bean, args);
    }

    public void store(MethodInvocation methodInvocation, ExcelExport excelExport) {
        ExcelWriter excelWriter = EasyExcel.write().file(localFile).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("Sheet").build();

        final String queryMethod = excelExport.queryMethod();
        PageSwitcher pageSwitcher = new PageSwitcher();
        String pageNoDescription = excelExport.pageSwitch();
        try {
            Object[] arguments = methodInvocation.getArguments();
            pageSwitcher.resetPage(arguments, pageNoDescription);
            do {
                final Object queryResultData = invokeMethod(methodInvocation.getThis(), queryMethod,
                        methodInvocation.getMethod().getParameterTypes(),
                        arguments);
                List list = (List) PropertyFinder.getNestedProperty(queryResultData, excelExport.listFinder());
                if (list == null || list.isEmpty()) {
                    break;
                }
                excelWriter.write(list, writeSheet);


                arguments = pageSwitcher.nextPage(arguments, pageNoDescription);
            } while (true);
        } finally {
            // 关闭资源
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }
}
